<template>
    <div id="threepage"></div>
</template>
<script setup>
import { onMounted, onBeforeUnmount, watch } from "vue";
import { useCounterStore } from "../store";
import { ElLoading, ElMessage } from 'element-plus'
import ThreeData from '../assets/js/createThree'
import LoadModel from '../assets/js/loadModel'
import InitAnimation from '../assets/js/createAnimation'
import modelConfig from '../assets/js/modelConfig'

const store = useCounterStore();
let threeData = null
let loadModel = null
let initAnimation = null
let loading = null
let loadNum = 0


watch(() => store.controlType, (newValue, oldValue) => {
    threeData && threeData.changeControlType(newValue, oldValue);
}, { immediate: true })

watch(() => store.modeChange, (newValue, oldValue) => {
    if (newValue && threeData) {
        if (store.modeType) {
            threeData.css3DTitleGroup.visible = false;
            threeData.orbitControls.enablePan = false;
            store.buildName = threeData.buildGroup.children[0].name;
        } else {
            threeData.css3DTitleGroup.visible = true;
            threeData.orbitControls.enablePan = true;
            threeData.resetMode().then(res => {
                store.modeChange = false;
                store.buildName = '';
            })
        }
    } else {
        store.modeChange = false;
    }
})

watch(() => store.buildName, (newValue, oldValue) => {
    if (threeData && newValue != oldValue) {
        let newModel = threeData.buildGroup.getObjectByName(newValue)
        let oldModel = threeData.buildGroup.getObjectByName(oldValue)
        switch (newValue) {
            case '粗格栅及污水提升泵房':
                newModel.position.y += 0.1;
                break;
            default:
                break;
        }
        switch (oldValue) {
            case '粗格栅及污水提升泵房':
                oldModel.position.y -= 0.1
                break;
            default:
                break;
        }
        if(newModel){
            threeData.moveToBuild(newModel).then((res) => {
                if(oldValue == ''){
                    store.modeChange = false;
                }
            })
        }
    }
})

function loadMap() {
    loading = ElLoading.service({
        lock: true,
        text: '正在加载场景地图...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    loadModel.loadGlbModel(modelConfig).then((model) => {
        threeData.scene.add(model)
        ElMessage({
            message: `成功加载场景地图`,
            type: 'success',
            plain: true,
        })
        loading.setText('开始加载构筑物')
        modelConfig.children.forEach((obj) => {
            let el = model.getObjectByName(obj.name)
            if (el) {
                el.castShadow = false;
                let centerPostion = loadModel.getCenter(el)
                obj.position = {
                    x: centerPostion.x + obj.position.x,
                    y: centerPostion.y + obj.position.y,
                    z: centerPostion.z + obj.position.z
                }
                obj.maxsize = loadModel.getMaxSize(el)
                loadBuild(obj)
            }
        });
    }).catch((err) => {
        console.error(err)
        ElMessage({
            message: `场景地图加载失败`,
            type: 'error',
            plain: true,
        })
        loading.close()
    })
}

function loadBuild(obj) {
    loadModel.loadGlbModel(obj).then((model) => {
        threeData.buildGroup.add(model)
        threeData.createBuildTitle(model)
        model.traverse((child) => {
            if (child.name.includes('抓斗全')) {
                initAnimation.setZhuaDouAnimation(child)
            }
            if (child.name.includes('隔板')) {
                initAnimation.setgebanAnimation(child)
            }
        })
        loadNum += 1;
        loading.setText(`加载构筑物进度${loadNum}/${modelConfig.children.length}`)
        ElMessage({
            message: `成功加载${obj.name}`,
            type: 'success',
            plain: true,
        })
        if (loadNum == modelConfig.children.length) {
            loading.close()
        }
    }).catch((err) => {
        console.error(err)
        ElMessage({
            message: `构筑物${obj.name}加载失败`,
            type: 'error',
            plain: true,
        })
        loadNum += 1;
        if (loadNum == modelConfig.children.length) {
            loading.close()
        }
    })
}

onMounted(() => {
    const dom = document.getElementById('threepage')
    threeData = new ThreeData(dom)
    loadModel = new LoadModel()
    initAnimation = new InitAnimation(threeData)
    loadMap()
})
onBeforeUnmount(() => {
    threeData.beforeDestroy()
})
</script>
<style scoped lang="scss">
#threepage {
    width: 100vw;
    height: 100vh;
}
</style>